package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.*;
import cn.com.yx.ms.domain.dev.*;
import cn.com.yx.ms.domain.mq.MessageBase;
import cn.com.yx.ms.domain.mq.MqCommandType;
import cn.com.yx.ms.domain.mq.MqType;
import cn.com.yx.ms.domain.mq.downstream.D_Message2100;
import cn.com.yx.ms.domain.program.CatalogModel;
import cn.com.yx.ms.domain.template.*;
import cn.com.yx.ms.persistence.*;
import cn.com.yx.ms.service.*;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.configuration.MQSend;
import cn.yx.framework.util.DateUtil;
import cn.yx.framework.util.FileUtil;
import cn.yx.framework.util.HttpClientUtil;
import cn.yx.framework.util.ZipCompressor;
import cn.yx.framework.view.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class DevServiceImpl implements IDevService {

    @Resource
    private ISysService iSysService;
    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private DevCatalogMapper devCatalogMapper;
    @Resource
    private DevEquStoreMapper devEquStoreMapper;
    @Resource
    private DevVirtualCatalogMapMapper devVirtualCatalogMapMapper;
    @Resource
    private DevVersionRecordMapper devVersionRecordMapper;
    @Resource
    private DevImgMapper devImgMapper;
    @Resource
    private DevChannelNoMapper devChannelNoMapper;
    @Resource
    private UpDevUpdateReplayProgressMapper upDevUpdateReplayProgressMapper;
    @Resource
    private DevStatusMapper devStatusMapper;
    @Resource
    private ModelMainMapper modelMainMapper;
    @Resource
    private StlDevMapMapper stlDevMapMapper;
    @Resource
    private StlDevSyncMapper stlDevSyncMapper;
    @Resource
    private DevAlertInfoMapper devAlertInfoMapper;
    @Resource
    private MQSend mqSend;
    @Resource
    private StlMainMapper stlMainMapper;

//    @Resource
//    private MyWebSocket myWebSocket;

    // region << 设备目录 >>

    @Override
    public ApiResult saveDevCatalog(CatalogModel catalogModel) {
        ApiResult result = null;


        if (!StringUtils.isNoneBlank(catalogModel.getName())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "目录名称不能为空");
        }

        //判断同级下目录名称是否重复
        int countByName = devCatalogMapper.selectCountByCatalogName(catalogModel.getParentid(), catalogModel.getName());
        if (!StringUtils.isNoneBlank(catalogModel.getId()) && countByName > 0) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "同级目录下目录名不能重复，请重新输入");
        }

        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey(catalogModel.getId());
        if (devCatalog == null) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertDevCatalog(catalogModel));

        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateDevCatalog(catalogModel));

        }

        return result;
    }

    @Override
    public int insertDevCatalog(CatalogModel catalogModel) {
        DevCatalog devCatalog = new DevCatalog();

        if (!StringUtils.isNoneBlank(catalogModel.getId())) {
            catalogModel.setId(UUID.randomUUID().toString());
        }

        devCatalog.setGuid(catalogModel.getId());
        devCatalog.setName(catalogModel.getName());
        devCatalog.setParentid(catalogModel.getParentid());
        devCatalog.setLevel(0);
        devCatalog.setNumber(devCatalogMapper.getMaxNumber(catalogModel.getParentid()));
        devCatalog.setOrderindex(catalogModel.getOrderindex());
        devCatalog.setCreatetime(new Date());
        devCatalog.setUpdatetime(new Date());
        devCatalog.setIsdeleted(0);
        int result = devCatalogMapper.insert(devCatalog);
        if (result > 0) {
            iLogService.log("info",
                    "设备目录管理",
                    "创建成功-【" + JSON.toJSONString(devCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public ApiResult deleteDevCatalog(String id) {
        // int result = devCatalogMapper.deleteByPrimaryKey(id);
        ApiResult result = null;
        int count = 0;

        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey(id);
        if (devCatalog != null) {
            //判断目录是否存在子节点
            List<DevCatalog> childs = devCatalogMapper.selectChildByParentId(id);
            if (childs != null && childs.size() > 0) {
                return new ApiResult(AppConstant.MSG_FAILURE, false, "存在子目录，不允许删除");
            }

            //判断目录下是否存在设备
            List<DevEquStore> devChilds = devEquStoreMapper.findByParentId(id);
            if (devChilds != null && devChilds.size() > 0) {
                return new ApiResult(AppConstant.MSG_FAILURE, false, "该目录下存在设备，不允许删除");
            }

            devCatalog.setIsdeleted(1);
            count = devCatalogMapper.updateByPrimaryKey(devCatalog);

            if (count > 0) {
                iLogService.log("info",
                        "设备目录管理",
                        "删除成功-【" + id + "】-【" + devCatalog.getName() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }


        result = new ApiResult(AppConstant.MSG_SUCCESS, true, "删除成功");
        return result;
    }

    @Override
    public int updateDevCatalog(CatalogModel catalogModel) {
        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey(catalogModel.getId());
        devCatalog.setName(catalogModel.getName());
        devCatalog.setOrderindex(catalogModel.getOrderindex());
        devCatalog.setUpdatetime(new Date());
        devCatalog.setIsdeleted(0);
        int result = devCatalogMapper.updateByPrimaryKey(devCatalog);
        if (result > 0) {
            iLogService.log("info",
                    "设备目录管理",
                    "修改成功-【" + JSON.toJSONString(devCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public List<CatalogModel> findDevCatalogs(ApiQueryBase apiQueryBase) {
        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey("root");
        List<DevCatalog> devCatalogs = devCatalogMapper.find(apiQueryBase);
        List<CatalogModel> devCatalogModels = new ArrayList<CatalogModel>();

        //初始化根节点
        CatalogModel root = new CatalogModel();
        root.setId(devCatalog.getGuid());
        root.setName(devCatalog.getName());
        root.setNumber(devCatalog.getNumber());
        root.setChildren(new ArrayList<CatalogModel>());

        BuildDevCatalogTree(root, devCatalogs);

        if (root.getChildren() != null && root.getChildren().size() != 0) {
            root.setIsleaf(0);
        } else {
            root.setIsleaf(1);
        }

        devCatalogModels.add(root);
        return devCatalogModels;
    }

    private void BuildDevCatalogTree(CatalogModel node, List<DevCatalog> devCatalogs) {
        for (DevCatalog devCatalog :
                devCatalogs) {
            if (devCatalog.getParentid() != null && devCatalog.getParentid().equals(node.getId())) {
                CatalogModel child = new CatalogModel();
                child.setId(devCatalog.getGuid());
                child.setName(devCatalog.getName());
                child.setParentid(devCatalog.getParentid());
                child.setNumber(devCatalog.getNumber());
                child.setOrderindex(devCatalog.getOrderindex());
                child.setChildren(new ArrayList<CatalogModel>());
                child.setIsParent("true");
                //child.setNodetype("0");
                node.getChildren().add(child);

                //递归调用
                BuildDevCatalogTree(child, devCatalogs);
                if (child.getChildren() != null && child.getChildren().size() != 0) {
                    child.setIsleaf(0);
                } else {
                    child.setIsleaf(1);
                }
            }
        }

    }

    @Override
    public CatalogModel findDevCatalog(String id) {
        CatalogModel catalogModel = null;
        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey(id);
        if (devCatalog != null) {
            catalogModel = new CatalogModel();
            catalogModel.setId(devCatalog.getGuid());
            catalogModel.setParentid(devCatalog.getParentid());
            catalogModel.setName(devCatalog.getName());
            catalogModel.setOrderindex(devCatalog.getOrderindex());
        }
        return catalogModel;
    }

    // endregion

    // region << 设备管理 >>
    @Override
    public ApiResult saveDev(DevModel devModel) {
        ApiResult result = null;

        if (!StringUtils.isNoneBlank(devModel.getDevsn())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "请输入设备编号");
            return result;
        }

        //判断设备编号是否重复
        int count = devEquStoreMapper.selectCountByDevSn(devModel.getDevsn());
        if (!StringUtils.isNoneBlank(devModel.getGuid()) && count > 0) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "该设备号已存在，请重新输入");
            return result;
        }

        if (!StringUtils.isNoneBlank(devModel.getGuid())) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertDev(devModel));
        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateDev(devModel));
        }

        // 根据设备板卡序列号生成二维码
        String uniqueno = devModel.getHardwareuniqueno();
        iCommonService.generateQRCode(BaseConstant.getUploadConfig().getFilepath() + "/qrcode/", uniqueno, uniqueno);

        //dev_equ_stand 保存设备与站台关系

        return result;
    }

    @Override
    public ApiCode saveDevChannel(DevChannelModel devChannelModel) {
        ApiCode apiCode = ApiCode.APP_100200;
        if (devChannelModel != null) {
            if (StringUtils.isNoneBlank(devChannelModel.getDevsn())) {
                List<DevChannelNo> channels = devChannelNoMapper.findByDevsn(devChannelModel.getDevsn());
                boolean ishave = true;
                for (int i = 0; i < devChannelModel.getChannels().size(); i++) {
                    ishave = false;
                    for (DevChannelNo channel : channels) {
                        if (channel.getChannelno().equals(Integer.toString(i + 1))) {
                            ishave = true;
                            channel.setChannelname(devChannelModel.getChannels().get(i).getChannelname());
                            devChannelNoMapper.updateByPrimaryKey(channel);
                            break;
                        }
                    }
                    if (!ishave) {
                        DevChannelNo newChannel = new DevChannelNo();
                        newChannel.setGuid(UUID.randomUUID().toString());
                        newChannel.setDevSn(devChannelModel.getDevsn());
                        newChannel.setChannelno(Integer.toString(i + 1));
                        newChannel.setStatus("off");
                        newChannel.setChannelname(devChannelModel.getChannels().get(i).getChannelname());
                        devChannelNoMapper.insert(newChannel);
                    }
                }
            } else {
                // region 批量更新继电器
                List<DevChannelNo> channels = devChannelNoMapper.findAll();
                List<DevEquStore> devs = devEquStoreMapper.findAll();

                boolean ishave = false;
                for (DevEquStore dev : devs) {
                    ishave = false;
                    for (DevChannelNo channel : channels) {
                        if (StringUtils.isNoneBlank(channel.getDevSn()) && channel.getDevSn().equals(dev.getDevSn())) {
                            ishave = true;
                            for (DevChannelNo c : devChannelModel.getChannels()) {
                                if (StringUtils.isNoneBlank(c.getChannelno()) && c.getChannelno().equals(channel.getChannelno())) {
                                    channel.setChannelname(c.getChannelname());
                                    devChannelNoMapper.updateByPrimaryKey(channel);
                                    break;
                                }
                            }
                        }
                    }

                    if (!ishave) {
                        for (int i = 0; i < 8; i++) {
                            DevChannelNo newChannel = new DevChannelNo();
                            newChannel.setGuid(UUID.randomUUID().toString());
                            newChannel.setDevSn(dev.getDevSn());
                            newChannel.setChannelno((i + 1) + "");
                            newChannel.setStatus("off");
                            newChannel.setChannelname(devChannelModel.getChannels().get(i).getChannelname());
                            devChannelNoMapper.insert(newChannel);
                        }
                    } // end if
                } // end for

                // endregion
            }
        } else {
            apiCode = ApiCode.APP_101400;
        }
        return apiCode;
    }

    @Override
    public ApiResult findDevChannel(String devsn) {
        List<DevChannelNo> channelNos = devChannelNoMapper.findByDevsn(devsn);

        DevChannelModel result = new DevChannelModel();
        result.setDevsn(devsn);

        if (channelNos != null && channelNos.size() > 0) {
            result.setChannels(new ArrayList<>());
            for (DevChannelNo channelNo : channelNos) {
                result.getChannels().add(channelNo);
            }
        }


        return new ApiResult(AppConstant.MSG_SUCCESS, true, "", result);
    }

    @Override
    public int insertDev(DevModel devModel) {
        DevEquStore devEquStore = new DevEquStore();

        if (!StringUtils.isNoneBlank(devModel.getGuid())) {
            devModel.setGuid(UUID.randomUUID().toString());
        }

        devEquStore.setEquipmentguid(devModel.getGuid());
        devEquStore.setEquipmentno(devModel.getDevsn());
        devEquStore.setDevSn(devModel.getDevsn());
        devEquStore.setCreatetime(new Date());
        devEquStore.setCatalogid(devModel.getCatalogid());
        Integer count = devEquStoreMapper.selectCountAll();
        if (null == count) {
            devEquStore.setOrderindex(0);
        } else {
            devEquStore.setOrderindex(count);
        }
        devEquStore.setHardwareUniqueNo(devModel.getHardwareuniqueno());

        //保存设备信息
        int result = devEquStoreMapper.insert(devEquStore);
        if (result > 0) {
            iLogService.log("info",
                    "设备管理",
                    "创建成功-【" + JSON.toJSONString(devEquStore) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public int deleteDev(String id) {
        //找到该设备信息
        DevEquStore devEquStore = devEquStoreMapper.selectByguid(id);
        //删除
        int result = devEquStoreMapper.deleteByPrimaryKey(id);
        //根据序号查找
        List<DevEquStore> devEquStoreList = devEquStoreMapper.selectByOrderByOderIndexDesc(devEquStore.getOrderindex());
        if (devEquStoreList.size() > 0) {
            int orderIndex = devEquStore.getOrderindex();
            for (DevEquStore devEquStore1 : devEquStoreList) {
                devEquStore1.setOrderindex(orderIndex);
                devEquStoreMapper.updateByPrimaryKey(devEquStore1);
                orderIndex++;
            }
        }
        if (result > 0) {
            iLogService.log("info",
                    "设备管理",
                    "删除成功-【" + id + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public int updateDev(DevModel devModel) {
        DevEquStore devEquStore = devEquStoreMapper.selectByPrimaryKey(devModel.getGuid());
        devEquStore.setEquipmentno(devModel.getDevsn());
        devEquStore.setDevSn(devModel.getDevsn());
        devEquStore.setHardwareUniqueNo(devModel.getHardwareuniqueno());
        int result = devEquStoreMapper.updateByPrimaryKey(devEquStore);

        DevStatus devStatus = devStatusMapper.selectByPrimaryKey(devModel.getDevsn());
        if (devStatus != null) {
            devStatus.setDevSn(devModel.getDevsn());
            result += devStatusMapper.updateByPrimaryKey(devStatus);
        }

        if (result > 0) {
            iLogService.log("info",
                    "设备管理",
                    "修改成功-【" + JSON.toJSONString(devEquStore) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public List<DevEquStore> findDevs(ApiQueryBase apiQueryBase) {
        return devEquStoreMapper.find(apiQueryBase);
    }

    @Override
    public DevModel findDev(String id) {
        DevModel devModel = null;
        DevEquStore devEquStore = devEquStoreMapper.selectByPrimaryKey(id);
        if (devEquStore != null) {
            devModel = new DevModel();
            devModel.setGuid(devEquStore.getEquipmentguid());
            devModel.setDevsn(devEquStore.getEquipmentno());
            devModel.setCatalogid(devEquStore.getCatalogid());
            devModel.setHardwareuniqueno(devEquStore.getHardwareUniqueNo());
            devModel.setCreatetime(DateUtil.date2String(devEquStore.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return devModel;
    }


    // endregion

    // region << 设备监控 >>
    public List<DevCompleteInfoModel> findCompleteInfoModel(ApiQueryBase apiQueryBase) {
        return devEquStoreMapper.findDevCompleteModels(apiQueryBase);
    }

    public List<DevPositionAlertModel> findDevPositionAlerts() {
        return devEquStoreMapper.findDevPositionAlerts();
    }

    public List<DevPositionModel> findDevPositionModel(ApiQueryBase apiQueryBase) {
        return devEquStoreMapper.findDevPositionModels(apiQueryBase);
    }

    public List<DevPositionModel> findDevPositionModels() {
        return devEquStoreMapper.findDevPositionModels(null);
    }

    public DevCompleteInfoModel findOneDevCompleteModel(String devsn) {
        DevCompleteInfoModel result = devEquStoreMapper.findOneDevCompleteModel(devsn);
        result.setRelays(new ArrayList<>());
        //获取所有继电器
        List<DevChannelNo> channelNos = devChannelNoMapper.findByDevsn(devsn);
        //channelNos.sort((d1, d2) ->  d1.getChannelno().compareTo(d2.getChannelno()));
        Collections.sort(channelNos, Comparator.comparing(DevChannelNo::getChannelno));
        for (DevChannelNo dcn : channelNos) {
            if (StringUtils.isNoneBlank(dcn.getDevSn()) && dcn.getDevSn().equals(result.getDevsn())) {
                DevRelayModel drm = new DevRelayModel();
                drm.setChannelno(dcn.getChannelno());
                if (dcn.getStatus() != null)
                    drm.setStatus(dcn.getStatus().equals("on"));
                result.getRelays().add(drm);
            }
        }

        return result;
    }

    public DevImg findDevImg(String devsn) {
        return devImgMapper.selectByDevsn(devsn);
    }

    public DevOnlineCountModel findOnlineOfflineCount() {
        return devStatusMapper.findOnlineOfflineCount();
    }

    // endregion

    // region << 虚拟目录 >>

    public List<DevTreeModel> findDevTreeNodes() {
        EquipModel equipModel = null;
        List<EquipModel> equipModels = devEquStoreMapper.findEquipTree();
        List<DevTreeModel> devCatalogModels = new ArrayList<DevTreeModel>();

        for (EquipModel em :
                equipModels) {
            if (!StringUtils.isNoneBlank(em.getParentid())) {
                equipModel = em;
                break;
            }
        }

        //初始化根节点
        DevTreeModel root = new DevTreeModel();
        root.setId(equipModel.getGuid());
        root.setName(equipModel.getName());
        root.setParentid(equipModel.getParentid());
        root.setNodetype("0");
        root.setChildren(new ArrayList<DevTreeModel>());

        //递归调用
        BuildDevTree(root, equipModels);

        //添加树节点
        devCatalogModels.add(root);
        return devCatalogModels;
    }

    public List<DevTreeModel> findDevTreeNodesWithStyleName() {
        EquipModel equipModel = null;
        List<EquipModel> equipModels = devEquStoreMapper.findEquipTreeWithStyleName();
        List<DevTreeModel> devCatalogModels = new ArrayList<DevTreeModel>();

        for (EquipModel em :
                equipModels) {
            if (!StringUtils.isNoneBlank(em.getParentid())) {
                equipModel = em;
                break;
            }
        }

        //初始化根节点
        DevTreeModel root = new DevTreeModel();
        root.setId(equipModel.getGuid());
        root.setName(equipModel.getName());
        root.setParentid(equipModel.getParentid());
        root.setNodetype("0");
        root.setChildren(new ArrayList<DevTreeModel>());

        //递归调用
        BuildDevTree(root, equipModels);

        //添加树节点
        devCatalogModels.add(root);
        return devCatalogModels;
    }

    private void BuildDevTree(DevTreeModel node, List<EquipModel> equipModels) {
        for (EquipModel equipModel :
                equipModels) {
            if (equipModel.getParentid() != null && equipModel.getParentid().equals(node.getId())) {
                DevTreeModel child = new DevTreeModel();
                child.setId(equipModel.getGuid());
                child.setName(equipModel.getName());
                child.setParentid(equipModel.getParentid());
                child.setNodetype(equipModel.getNodetype());
                child.setDevsn(equipModel.getDevsn());
                child.setChildren(new ArrayList<DevTreeModel>());
                node.getChildren().add(child);

                //递归调用
                BuildDevTree(child, equipModels);

            }
        }

    }

    public List<DevTreeModel> findDevVirtualTreeNodes() {
        EquipModel equipModel = null;
        List<EquipModel> equipModels = devEquStoreMapper.findVirtualEquipTree();
        List<DevTreeModel> devCatalogModels = new ArrayList<DevTreeModel>();

        for (EquipModel em :
                equipModels) {
            if (!StringUtils.isNoneBlank(em.getParentid())) {
                equipModel = em;
                break;
            }
        }

        if (equipModel == null) {
            equipModel = new EquipModel();
            equipModel.setGuid("0");
            equipModel.setName("虚拟目录");
            equipModel.setNodetype("0");
        }

        //初始化根节点
        DevTreeModel root = new DevTreeModel();
        root.setId(equipModel.getGuid());
        root.setName(equipModel.getName());
        root.setParentid(equipModel.getParentid());
        root.setNodetype("0");
        root.setChildren(new ArrayList<DevTreeModel>());

        //递归调用
        BuildDevTree(root, equipModels);

        //添加树节点
        devCatalogModels.add(root);
        return devCatalogModels;
    }

    @Override
    public List<DevTreeModel> findDevVirtualTreeNodesWithStyle(String styleid) {
        EquipModel equipModel = null;
        List<EquipModel> equipModels = devEquStoreMapper.findVirtualEquipTree();
        //获得该式样的设备信息
        List<DevCatalog> devNameModel = stlMainMapper.getDevByStyleid(styleid);
        if (equipModels.size() > 0 && devNameModel.size() > 0) {
            //除去虚拟目录中,未被选中的设备
            boolean flag = false;
            for (int i = 0; i < equipModels.size(); i++) {
                if (null != equipModels.get(i).getDevsn() && !equipModels.get(i).getDevsn().equals("")) {
                    flag = false;
                    for (int j = 0; j < devNameModel.size(); j++) {
                        if (equipModels.get(i).getDevsn().equals(devNameModel.get(j).getGuid())) {
                            flag = true;
                        }
                    }
                    //判断是否存在
                    if (!flag) {
                        equipModels.remove(i);
                        i--;
                    }
                }
            }
            //去除没有设备的目录equipModels
            //得到设备信息
            List<EquipModel> equipModelList = new ArrayList<EquipModel>();
            for (int i = 0; i < equipModels.size(); i++) {
                if (null != equipModels.get(i).getDevsn() && !equipModels.get(i).getDevsn().equals("")) {
                    equipModelList.add(equipModels.get(i));
                }
            }
            //得到目录信息
            List<EquipModel> equipModelList1 = new ArrayList<EquipModel>();
            for (EquipModel equipModel1 : equipModels) {
                if (null == equipModel1.getDevsn() || equipModel1.getDevsn().equals("")) {
                    if (null != equipModel1.getParentid() && !equipModel1.getParentid().equals("")) {
                        equipModelList1.add(equipModel1);
                    }
                }
            }

            //判断目录是否存在设备
            boolean devFlag = false;
            List<EquipModel> equipModelList2 = new ArrayList<EquipModel>();
            for (int i = 0; i < equipModelList1.size(); i++) {
                devFlag = false;
                for (int j = 0; j < equipModelList.size(); j++) {
                    if (equipModelList1.get(i).getGuid().equals(equipModelList.get(j).getParentid())) {
                        devFlag = true;
                    }
                }
                if (!devFlag) {
                    equipModelList2.add(equipModelList1.get(i));
                }
            }
            //去除没有设备的目录
            boolean equFlag = false;
            for (int i = 0; i < equipModels.size(); i++) {
                equFlag = false;
                for (int j = 0; j < equipModelList2.size(); j++) {
                    if (equipModels.get(i).getGuid().equals(equipModelList2.get(j).getGuid())) {
                        equFlag = true;
                    }
                }
                if (equFlag) {
                    equipModels.remove(i);
                    i--;
                }
            }

        }


        List<DevTreeModel> devCatalogModels = new ArrayList<DevTreeModel>();

        for (EquipModel em :
                equipModels) {
            if (!StringUtils.isNoneBlank(em.getParentid())) {
                equipModel = em;
                break;
            }
        }

        if (equipModel == null) {
            equipModel = new EquipModel();
            equipModel.setGuid("0");
            equipModel.setName("虚拟目录");
            equipModel.setNodetype("0");
        }

        //初始化根节点
        DevTreeModel root = new DevTreeModel();
        root.setId(equipModel.getGuid());
        root.setName(equipModel.getName());
        root.setParentid(equipModel.getParentid());
        root.setNodetype("0");
        root.setChildren(new ArrayList<DevTreeModel>());

        //递归调用
        BuildDevTree(root, equipModels);

        //添加树节点
        devCatalogModels.add(root);
        return devCatalogModels;
    }

    public List<DevTreeModel> findDevVirtualTreeNodesWithStyle() {
        EquipModel equipModel = null;
        List<EquipModel> equipModels = devEquStoreMapper.findVirtualEquipTreeWithStyleName();
        List<DevTreeModel> devCatalogModels = new ArrayList<DevTreeModel>();

        for (EquipModel em :
                equipModels) {
            if (!StringUtils.isNoneBlank(em.getParentid())) {
                equipModel = em;
                break;
            }
        }

        if (equipModel == null) {
            equipModel = new EquipModel();
            equipModel.setGuid("0");
            equipModel.setName("虚拟目录");
            equipModel.setNodetype("0");
        }

        //初始化根节点
        DevTreeModel root = new DevTreeModel();
        root.setId(equipModel.getGuid());
        root.setName(equipModel.getName());
        root.setParentid(equipModel.getParentid());
        root.setNodetype("0");
        root.setChildren(new ArrayList<DevTreeModel>());

        //递归调用
        BuildDevTree(root, equipModels);

        //添加树节点
        devCatalogModels.add(root);
        return devCatalogModels;
    }

    public ApiResult saveVirtualDev(List<DevTreeModel> devTreeModels) {
        devEquStoreMapper.deleteVirtualCatalogMap();
        saveChildNodes(devTreeModels);

        iLogService.log("info",
                "虚拟目录",
                "调整成功-【" + JSON.toJSONString(devTreeModels) + "】",
                iUserContextService.getUserContext().getId());

        return new ApiResult(AppConstant.MSG_SUCCESS, true, "", null);
    }

    private void saveChildNodes(List<DevTreeModel> childNodes) {
        int orderindex = 0;

        for (DevTreeModel node : childNodes) {
            //todo save node
            DevVirtualCatalogMap dvm = new DevVirtualCatalogMap();
            dvm.setGuid(node.getNodetype().equals("0") ? node.gettId() : UUID.randomUUID().toString());
            dvm.setName(node.getName());
            dvm.setParentid(node.getParentTId());
            dvm.setLevel(node.getLevel());
            dvm.setOrderindex(orderindex++);
            dvm.setCreatetime(new Date());
            dvm.setNtype(node.getNodetype());
            dvm.setDevsn(node.getDevsn());
            devVirtualCatalogMapMapper.insert(dvm);

            if (node.getChildren() != null && node.getChildren().size() > 0) {
                saveChildNodes(node.getChildren());
            }
        }
    }
    // endregion

    // region << 设备升级 >>

    @Override
    public ApiResult saveDevVersionRecord(String version, String updatePackageName) {
        ApiResult result = null;

        DevVersionRecord devVersionRecord = devVersionRecordMapper.selectByVersion(version);

        if (devVersionRecord != null) {
            devVersionRecordMapper.deleteByVersion(version);
        }

        devVersionRecord = new DevVersionRecord();
        devVersionRecord.setGuid(UUID.randomUUID().toString());
        devVersionRecord.setVersion(version);
        devVersionRecord.setApkpath(updatePackageName);
        devVersionRecord.setCreatetime(new Date());

        int count = insertDevVersionRecord(devVersionRecord);
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "", count > 0 ? devVersionRecord.getGuid() : "");

    }

    @Override
    public int insertDevVersionRecord(DevVersionRecord devVersionRecord) {
        int result = devVersionRecordMapper.insert(devVersionRecord);
//        if (result > 0) {
//            iLogService.log("info",
//                    "设备升级",
//                    "创建成功-【" + JSON.toJSONString(devVersionRecord) + "】",
//                    iUserContextService.getUserContext().getId());
//        }
        return result;
    }

    @Override
    public int deleteUpdatePackage(String id) {
        return devVersionRecordMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateDevVersionRecord(DevVersionRecord devVersionRecord) {
        return devVersionRecordMapper.updateByPrimaryKey(devVersionRecord);
    }

    @Override
    public List<DevVersionRecord> findDevVersionRecord(ApiQueryBase query) {
        return devVersionRecordMapper.findAllDevVersionRecord();
    }

    @Override
    public List<UpDevUpdateLogModel> findUpDevUpdateLogs(ApiQueryBase query) {
        return upDevUpdateReplayProgressMapper.findUpDevUpdateLogs(query);
    }
    // endregion

    // region << 模板设备同步 >>
    public List<DevTemplate> findDevTemplates(String devid, String styleid) {
        return modelMainMapper.findDevTemplates(devid, styleid);
    }

    /**
     * 1.获取设备所关联式样对应的模板编号
     * 2.创建设备ID目录并赋值模板于对应设备ID目录下
     * 3.遍历设备成Media.json,Line.json,notice.json并写入设备目录下
     * 4.打包模板目录
     *
     * @param devid
     * @param styleid
     * @return
     * @throws Exception
     */
    public ApiCode syncDevTemplate(String devid, String styleid, String isDeleteLocalResource) throws Exception {
        ApiCode apiCode = ApiCode.APP_100200;
        if (!StringUtils.isNoneBlank(styleid)) {
            StlDevMap stlDevMap = stlDevMapMapper.findOneByDevId(devid);
            if (stlDevMap == null) {
                apiCode = ApiCode.APP_120500;
            } else {
                styleid = stlDevMap.getStyleid();
            }
        }

        if (apiCode.equals(ApiCode.APP_100200)) {
            // 同步生成每个设备的模板目录
            syncDevTemplate(devid, styleid, false, -1);

            // 通知设备下载模板（模板文件不包含）
            apiCode = htmlZipPush(devid, styleid, isDeleteLocalResource);
        }
        return apiCode;
    }


    public EquipmentNoAndStyleIdModel findEquipmentNoAndStyleId(String uniqueNo) throws Exception {
        EquipmentNoAndStyleIdModel noAndStyleId = new EquipmentNoAndStyleIdModel();
        DevEquStore devEquStore = devEquStoreMapper.selectByHardwareUniqueNo(uniqueNo);

        if (devEquStore != null) {
            noAndStyleId.setEquipmentno(devEquStore.getEquipmentno());
        }
        return noAndStyleId;
    }

    public ApiCode syncDevTemplate(String devid, String styleid, boolean isSendWs, int sendWsType) throws Exception {
        ApiCode apiCode = ApiCode.APP_100200;
        DevEquStore dev = devEquStoreMapper.selectByDevSn(devid);
        if (dev == null) {
            apiCode = ApiCode.APP_101400;
            return apiCode;
        }
        List<DevRegionModel> devRegionModels = modelMainMapper.findDevRegions(devid);
        List<DevResourceModel> devResourceModels = modelMainMapper.findDevResource(devid);
        List<DevNoticeModel> devNoticeModels = modelMainMapper.findDevNotice(devid);

        if (!StringUtils.isNoneBlank(styleid)) {
            StlDevMap stlDevMap = stlDevMapMapper.findOneByDevId(devid);
            if (stlDevMap == null) {
                apiCode = ApiCode.APP_120500;
            } else {
                styleid = stlDevMap.getStyleid();
            }
        }

        if (apiCode.equals(ApiCode.APP_100200)) {
            List<DevTemplate> devTemplates = modelMainMapper.findDevTemplates(devid, styleid);
            // 设备目录
            String path = BaseConstant.getUploadConfig().getFilepath() + "/template/devs/";

            // template/devs/ 目录下创建文件件

            // 创建设备模板目录
            File dir = new File(path + dev.getDevSn());
            if (!dir.exists()) {
                dir.mkdirs();//可创建多级目录，而mkdir()只能创建一级目录
            }

            // 复制模板至设备目录下
            for (DevTemplate dt : devTemplates) {
                if (dt.getDevsn().equals(dev.getDevSn())) {
                    String devPath = BaseConstant.getUploadConfig().getFilepath() + "/template/" + dt.getModelno();
                    File file = new File(devPath);
                    File file2 = new File(path + dev.getDevSn() + "/" + dt.getModelno());
                    FileUtil.copyFile(file, file2);

                    List<RegionModel> regionModels2010 = getMediaJsonObject(devRegionModels, devResourceModels);
                    List<RegionModel> regionModels2011 = getNoticeJsonObject(devRegionModels, devNoticeModels);
                    List<LineModel> lineModels = getLineJsonObject(dt.getDevsn());
                    DevConfigModel devConfigModel = new DevConfigModel();
                    devConfigModel.setDevid(devid);
                    devConfigModel.setStyleid(styleid);
                    devConfigModel.setServeraddress(iSysService.findGlobalConfig().getServeraddress());

                    String mediaJson = JSON.toJSONString(regionModels2010);
                    String noticeJson = JSON.toJSONString(regionModels2011);
                    String lineJson = JSON.toJSONString(lineModels);
                    String configJson = JSON.toJSONString(devConfigModel);


                    FileUtil.writeFile(path + dev.getDevSn() + "/" + dt.getModelno() + "/json", "config.json", ("var configjson = " + configJson).getBytes("UTF-8"));
                    FileUtil.writeFile(path + dev.getDevSn() + "/" + dt.getModelno() + "/json", "media.json", ("var mediajson = " + mediaJson).getBytes("UTF-8"));
                    FileUtil.writeFile(path + dev.getDevSn() + "/" + dt.getModelno() + "/json", "notice.json", ("var noticejson = " + noticeJson).getBytes("UTF-8"));
                    FileUtil.writeFile(path + dev.getDevSn() + "/" + dt.getModelno() + "/json", "line.json", ("var linejson = " + lineJson).getBytes("UTF-8"));

                    // 生成设备模板压缩包
                    ZipCompressor zipCompressor = new ZipCompressor(path + dev.getDevSn() + "/" + dt.getModelno() + ".zip");
                    zipCompressor.compressExe(path + dev.getDevSn() + "/" + dt.getModelno());

                    if (isSendWs) {
                        if (sendWsType == -1) {

                            /* 批量推送时,每个设备已经存在了json文件，无需再次发送 */
//                            mqSend.sendMsg(dev.getDevSn(), MqCommandType.C2010, mediaJson);
//                            mqSend.sendMsg(dev.getDevSn(), MqCommandType.C2011, noticeJson);
//                            mqSend.sendMsg(dev.getDevSn(), MqCommandType.C5011, lineJson);

                        } else {
                            switch (sendWsType) {
                                case 0: // 媒体
                                    MessageBase<List<RegionModel>> m2010 = new MessageBase<>();
                                    m2010.setMsgid(UUID.randomUUID().toString());
                                    m2010.setDeviceid(dev.getDevSn());
                                    m2010.setCommand(MqCommandType.C2010.getIndex());
                                    m2010.setType(MqType.response.getName());
                                    m2010.setContent(regionModels2010);
                                    // MyWebSocket.sendInfo(dev.getDevSn(), JSON.toJSONString(m2010));
                                    mqSend.sendMsg(dev.getDevSn(), MqCommandType.C2011, JSON.toJSONString(m2010));
                                    break;
                                case 1: // 公告
                                    MessageBase<List<RegionModel>> m2011 = new MessageBase<>();
                                    m2011.setMsgid(UUID.randomUUID().toString());
                                    m2011.setDeviceid(dev.getDevSn());
                                    m2011.setCommand(MqCommandType.C2011.getIndex());
                                    m2011.setType(MqType.response.getName());
                                    m2011.setContent(regionModels2011);
                                    // MyWebSocket.sendInfo(dev.getDevSn(), JSON.toJSONString(m2011));
                                    mqSend.sendMsg(dev.getDevSn(), MqCommandType.C2011, JSON.toJSONString(m2011));

                                    // 解析测试
//                                    String test = "{\"command\":2011,\"content\":[{\"count\":4,\"regioncode\":\"REGION_NOTICE_A\",\"resources\":[{\"data\":{\"content\":\"测试删除公告01测试删除公告01测试删除公告01\"},\"name\":\"\",\"orderindex\":1,\"type\":\"notice\"},{\"data\":{\"content\":\"我们提供了通用的项目模板，你可以直接使用。对于熟悉 cooking 或 Laravel 的用户，我们也准备了相应的模板，同样可以直接下载使用。\"},\"name\":\"\",\"orderindex\":0,\"type\":\"notice\"},{\"data\":{\"content\":\"12月1日，“2016年中国最具幸福感城市”调查推选活动公布结果：成都、杭州、南京、西安、长春、长沙、苏州、珠海、北京、上海获前十排名。本届评选以“人民获得感”为主题，自6月来累计超1128万人次参与。\"},\"name\":\"\",\"orderindex\":0,\"type\":\"notice\"},{\"data\":{\"content\":\"由于电子站牌升级安装调试，给您带来不便敬请谅解！ 各线路的完整纸质线路牌张贴在站牌下方及背面，如有需要请查询。\"},\"name\":\"\",\"orderindex\":0,\"type\":\"notice\"}]}],\"deviceid\":\"192.168.101.66\",\"msgid\":\"1b663588-f61c-4da7-b436-5e2befb626be\",\"type\":\"response\"}";
//
//                                    MessageBase<List<RegionModel>> m2 = JSON.parseObject(test, new TypeReference<MessageBase<List<RegionModel>>>() {
//                                    });

                                    break;
                                case 2: // 线路
                                    // MyWebSocket.sendInfo(dev.getDevSn(), lineJson);
                                    MessageBase<List<LineModel>> m5011 = new MessageBase<>();
                                    m5011.setMsgid(UUID.randomUUID().toString());
                                    m5011.setDeviceid(dev.getDevSn());
                                    m5011.setCommand(MqCommandType.C5011.getIndex());
                                    m5011.setType(MqType.response.getName());
                                    m5011.setContent(lineModels);
                                    mqSend.sendMsg(dev.getDevSn(), MqCommandType.C5011, JSON.toJSONString(m5011));
                                    break;
                            }
                        }
                    }
                }
            }
        }
        return apiCode;
    }

    /**
     * 生成多媒体JSON对象
     *
     * @param devRegionModels
     * @param devResourceModels
     * @return
     */
    private List<RegionModel> getMediaJsonObject(List<DevRegionModel> devRegionModels, List<DevResourceModel> devResourceModels) {
        List<RegionModel> regionModels = new ArrayList<>();
        for (DevRegionModel devRegionModel : devRegionModels) {
            if (devRegionModel.getAreano().contains("VIDEO")) {


                RegionModel region = new RegionModel();
                region.setRegioncode(devRegionModel.getAreano());
                region.setCount(devResourceModels.size());

                // region << 添加资源文件 >>

                List<ResourceModel> resourceModels = new ArrayList<>();
                for (DevResourceModel devResourceModel : devResourceModels) {
                    if (devResourceModel.getRegioncode().equals(devRegionModel.getAreano())) {
                        if (devResourceModel.getRegioncode().contains("VIDEO")) {
                            String localPath = FileUtil.getFileName(devResourceModel.getFilepath());
                            String resourceUrl = "/" + devResourceModel.getFilepath();
                            if (devResourceModel.getRtype().equals("0") || devResourceModel.getRtype().equals("1")) {
                                ResourceModel<VideoModel> resourceVideo = new ResourceModel<VideoModel>();
                                resourceVideo.setName("");
                                resourceVideo.setType("video");
                                resourceVideo.setOrderindex(devResourceModel.getOrderindex());
                                VideoModel videoModel = new VideoModel();
                                videoModel.setVideotype(Integer.parseInt(devResourceModel.getRtype()));
                                videoModel.setStart(devResourceModel.getStart());
                                videoModel.setEnd(devResourceModel.getEnd());
                                videoModel.setUrl(resourceUrl);
                                videoModel.setLocalpath("resource/video/" + localPath);
                                resourceVideo.setData(videoModel);
                                resourceModels.add(resourceVideo);
                            } else {
                                ResourceModel<ImageModel> resourceImage = new ResourceModel<ImageModel>();
                                resourceImage.setName("");
                                resourceImage.setType("image");
                                resourceImage.setOrderindex(devResourceModel.getOrderindex());
                                ImageModel imageModel = new ImageModel();
                                imageModel.setUrl(resourceUrl);
                                imageModel.setLocalpath("resource/image/" + localPath);
                                resourceImage.setData(imageModel);
                                resourceModels.add(resourceImage);
                            }
                        }
                    }
                }

                // endregion

                region.setResources(resourceModels);
                regionModels.add(region);
            }
        }
        return regionModels;
    }

    /**
     * 生成公告JSON对象
     *
     * @param devRegionModels
     * @param devNoticeModels
     * @return
     */
    private List<RegionModel> getNoticeJsonObject(List<DevRegionModel> devRegionModels, List<DevNoticeModel> devNoticeModels) {
        List<RegionModel> regionModels = new ArrayList<>();

        for (DevRegionModel devRegionModel : devRegionModels) {

            if (devRegionModel.getAreano().contains("NOTICE")) {


                RegionModel region = new RegionModel();
                region.setRegioncode(devRegionModel.getAreano());
                region.setCount(devNoticeModels.size());

                // region << 添加公告文件 >>

                List<ResourceModel> resourceModels = new ArrayList<>();
                for (DevNoticeModel devNoticeModel : devNoticeModels) {
                    ResourceModel<NoticeModel> resourceNotice = new ResourceModel<NoticeModel>();
                    resourceNotice.setName("");
                    resourceNotice.setType("notice");
                    resourceNotice.setOrderindex(devNoticeModel.getOrderindex());

                    NoticeModel noticeModel = new NoticeModel();
                    noticeModel.setContent(devNoticeModel.getContent());
                    resourceNotice.setData(noticeModel);

                    resourceModels.add(resourceNotice);
                }

                // endregion
                region.setResources(resourceModels);
                regionModels.add(region);
            }
        }

        return regionModels;
    }

    /**
     * 获取线路信息数据
     *
     * @param devid
     * @return
     * @throws Exception
     */
    private List<LineModel> getLineJsonObject(String devid) throws Exception {
        List<LineModel> lineModels = new ArrayList<>();

        String response = HttpClientUtil.sendGet(BaseConstant.getBusApiConfig().getUrl(), "deviceid=" + devid + "&command=5001");
        MessageBase<List<LineModel>> lineModelMessageBase = JSON.parseObject(response, new TypeReference<MessageBase<List<LineModel>>>() {
        });

        lineModels = lineModelMessageBase.getContent();
        return lineModels;
    }

    public ApiCode htmlZipPush(String devid, String styleid, String isDeleteLocalResource) throws Exception {
        ApiCode apiCode = ApiCode.APP_100200;

        // 获取式样下当前默认模板
        ModelMain modelMain = modelMainMapper.findDefaultModelByStyleId(styleid);

        MessageBase<D_Message2100> m2100 = new MessageBase<>();
        m2100.setMsgid(UUID.randomUUID().toString());
        m2100.setDeviceid(devid);
        m2100.setCommand(MqCommandType.C2100.getIndex());
        m2100.setType(MqType.response.toString());

        D_Message2100 dm2100 = new D_Message2100();
        dm2100.setDevid(devid);
        // dm2100.setDownpath(URLEncoder.encode("template/" + modelMain.getNo() + ".zip", "utf-8"));
        dm2100.setDownpath("/template/devs/" + devid + "/" + modelMain.getNo() + ".zip");
        dm2100.setDirect(modelMain.getDirect());
        dm2100.setIsdeletelocal(isDeleteLocalResource);
        m2100.setContent(dm2100);

        // websocket发送
        // MyWebSocket.sendInfo(devid, JSON.toJSONString(m2100));
        mqSend.sendMsg(devid, MqCommandType.C2100, JSON.toJSONString(m2100));

        // 记录同步
        StlDevSync stlDevSync = new StlDevSync();
        stlDevSync.setGuid(UUID.randomUUID().toString());
        stlDevSync.setDevid(devid);
        stlDevSync.setStyleid(styleid);
        stlDevSync.setModelid(modelMain.getGuid());
        stlDevSync.setStart(new Date());
        stlDevSync.setState(0);
        stlDevSync.setCreatetime(new Date());
        stlDevSyncMapper.insert(stlDevSync);

        return apiCode;
    }

    /**
     * 根据设备编号获得设备升级日志
     *
     * @param devsn
     * @return
     */
    public List<DevUpdateReplayProgress> findDevUpdateReplayProgress(String devsn) {
        return upDevUpdateReplayProgressMapper.findBydevsn(devsn);
    }

    /**
     * 设备转移
     *
     * @param catalogModels
     * @return
     */
    @Override
    public ApiCode saveEqusByMove(List<CatalogModel> catalogModels) {
        ApiQueryBase query = new ApiQueryBase();
        List<CatalogModel> catalogModelList = findDevCatalogs(query);
        //System.out.println("原始的设备目录:"+catalogModelList);
        //System.out.println("修改后的设备目录"+catalogModels);
        catalogModels = catalogModels.get(0).getChildren();
        //得到tId的长度
        //catalogModelList=catalogModelList.get(0).getChildren();
//        CatalogModel catalogModel=catalogModels.get(0);
//        System.out.println(catalogModel);
//        int tIdLength=catalogModel.gettId().length();


        //System.out.println("长度:"+catalogModels.size());
        List<CatalogModel> catalogModelList1 = findAddCatalogModel(catalogModels);
        //System.out.println("遍历后的集合:"+catalogModelList1);
        //ApiCode apiCode=findAndSaveDevEquStore(catalogModelList1,tIdLength);
        //List<CatalogModel> catalogModelList2=
        //System.out.println(catalogModelList2.size());
        return findAndSaveDevEquStore(catalogModelList1);
    }

    /**
     * 遍历集合,放入一个对象中
     *
     * @param catalogModels
     * @return
     */
    public List<CatalogModel> findAddCatalogModel(List<CatalogModel> catalogModels) {
        List<CatalogModel> catalogModelList = new ArrayList<CatalogModel>();
        //修改后的设备目录catalogModels
        for (CatalogModel catalogModels1 : catalogModels) {
            catalogModelList.add(catalogModels1);
            //children长度不等于0
            if (null != catalogModels1.getChildren() && catalogModels1.getChildren().size() != 0) {
                List<CatalogModel> catalogModels2 = findAddCatalogModel(catalogModels1.getChildren());
                catalogModelList.addAll(catalogModels2);
            }
        }
        return catalogModelList;
    }

    /**
     * 区分出设备信息,修改设备信息
     *
     * @param catalogModelList
     * @return
     */
    public ApiCode findAndSaveDevEquStore(List<CatalogModel> catalogModelList) {
        List<CatalogModel> catalogModels = new ArrayList<CatalogModel>();
        List<CatalogModel> catalogModels1 = new ArrayList<CatalogModel>();
        for (CatalogModel catalogModel : catalogModelList) {
            if (null != catalogModel.getNumber() && catalogModel.getNumber().equals("ip")) {
                catalogModels.add(catalogModel);
            }
        }
        if (catalogModels.size() != 0) {
            for (CatalogModel catalogModel : catalogModels) {
                for (CatalogModel catalogModel1 : catalogModelList) {
                    if (null == catalogModel1.getNumber() || !catalogModel1.getNumber().equals("ip")) {
                        if (catalogModel.getParentTId().equals(catalogModel1.gettId())) {
                            //System.out.println(catalogModel.getParentTId());
                            //System.out.println(catalogModel1.gettId());
                            catalogModel.setParentid(catalogModel1.getId());
                            catalogModels1.add(catalogModel);
                        }
                    }
                }
            }
        }
        //System.out.println(catalogModels1);
        //修改表dev_equ_store
        for (CatalogModel catalogModel : catalogModels1) {
            DevEquStore devEquStore = devEquStoreMapper.selectByguid(catalogModel.getId());
            devEquStore.setDevSn(devEquStore.getEquipmentno());
            devEquStore.setCatalogid(catalogModel.getParentid());
            devEquStoreMapper.updateDevEquStore2(devEquStore);
            //System.out.println(catalogModel.getParentid());
        }
        return ApiCode.APP_500500;
    }

    // endregion

    // region << 设备告警 >>

    @Override
    public List<DevAlertInfoModel> findDevAlertInfos(ApiQueryBase query) {
        return devAlertInfoMapper.find(query);
    }

    @Override
    public int findDevAlertCount() {
        return devAlertInfoMapper.findAlertCount();
    }

    @Override
    public ApiCode revokeAlerts(List<DevAlertInfoModel> list) {
        ApiCode apiCode = ApiCode.APP_600500;
        if (list.size() == 0) {
            //撤销告警为空
            return ApiCode.APP_601500;
        }
        //撤回告警
        for (DevAlertInfoModel devAlertInfoModel : list) {
            devAlertInfoMapper.updateAlert(devAlertInfoModel);
        }
        return apiCode;
    }

    // endregion
}